package com.taiji.dicom4platform.common.security.provider;

import cn.hutool.core.bean.BeanUtil;
import com.taiji.dicom4platform.common.model.entity.SysUser;
import com.taiji.dicom4platform.common.security.model.CommonUserDetails;
import com.taiji.dicom4platform.common.security.service.IUserDetailService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/5/20
 **/
@Slf4j
@Configuration
@AllArgsConstructor
public class SecurityAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserDetailService iUserDetailService;

    public SecurityAuthenticationProvider(){

    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        SysUser sysUser = iUserDetailService.getByUsername(authentication.getPrincipal().toString());
        CommonUserDetails userDetails = new CommonUserDetails();
        BeanUtil.copyProperties(sysUser,userDetails);
        additionalAuthenticationChecks(userDetails,token);
        return authentication;
    }
    protected void additionalAuthenticationChecks(UserDetails userDetails,
                                                  UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            throw new BadCredentialsException( "Bad credentials");
        }
        String presentedPassword = authentication.getCredentials().toString();
        if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
            throw new BadCredentialsException("Bad credentials");
        }
    }
    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}
